
$().ready(function() {
	
});

var urlFormObj = document.getElementById("urlForm");


function showCode(str, co) {
	// var codeDiv = document.createElement("div");
	var codeAera = document.createElement("pre");

	//codeAera.name = "code";
	//codeAera.setAttribute('name', 'code'); // ff下须如此

	codeAera.className = "brush: js";
//	codeAera.id = 'script_div';

	// co.appendChild(codeDiv);
	co.appendChild(codeAera);

	codeAera.innerHTML = str;
	console.log(SyntaxHighlighter.highlight);
	SyntaxHighlighter.highlight();
}

function formatJson(jsonStr) {
	return jsonStr;
}








var idIndex = 0;



// addField('headerTable', 'headerTableBody', 'header', '', '',
// '${ctx}/app-res/common/httpclient/httpHeaders.json');
// addField('fieldTable', 'fieldTableBody', 'param');
function addField(tableId, tableBodyId, prefix, nameValue, valueValue, remarkValue, autoCompleteUrl) {



	var tableBody = document.getElementById(tableBodyId);
	var row = tableBody.insertRow(tableBody.rows.length);

	
	
	
	var cell = document.createElement("td");
//	row.appendChild(cell);
//	var inputEle3 = talent.Util.createInputElement("checkbox");
//	cell.appendChild(inputEle3);
	
	
//	cell = document.createElement("td");
	row.appendChild(cell);
	var inputEle1 = document.createTextNode(nameValue ? nameValue : "");//talent.Util.createInputElement("text");
	cell.appendChild(inputEle1);
	cell.style.width = "100px";
//	inputEle1.setAttribute("name", prefix + "_name");
//	inputEle1.style.width = "100px";
//	inputEle1.value = nameValue ? nameValue : "";
//	inputEle1.id = "name__ujh" + idIndex++;

	cell = document.createElement("td");// theadRow.insertCell(theadRow.cells.length);
	row.appendChild(cell);
	var inputEle2 = document.createTextNode(valueValue ? valueValue : "");;
	cell.appendChild(inputEle2);
	cell.style.width = "400px";
//	inputEle2.setAttribute("name", prefix + "_value");
//	inputEle2.style.width = "400px";
//	inputEle2.value = valueValue ? valueValue : "";
//	inputEle2.id = "value__ujh" + idIndex++;
	
	
	cell = document.createElement("td");// theadRow.insertCell(theadRow.cells.length);
	row.appendChild(cell);
	var inputEle2 = document.createTextNode(remarkValue ? remarkValue : "");;
	cell.appendChild(inputEle2);
	cell.style.width = "400px";


	

}

// removeField('headerTable', 'headerTableBody', 'header');
// removeField('fieldTable', 'fieldTableBody', 'param');
function removeField(tableId, tableBodyId, prefix, deleteAll) {
	var table = document.getElementById(tableBodyId);

	var rowCount = table.rows.length;
	for (var i = 0; i < rowCount; i++) {
		var row = table.rows[i];

		if (row.cells[0]) {
			var chkbox = row.cells[0].childNodes[0];
			if (deleteAll || (null != chkbox && true == chkbox.checked)) {
				table.deleteRow(i);
				rowCount--;
				i--;
			}
		}
	}
}

var OperHandler = function(config) {
	/**
	 * 删除数据
	 */
	this.del = function() {
		deleteTemplate('urlForm', config);
	};

};

function operRender(conf) {

}

var operField = {
	name : "oper",
	label : "操作",
	dataCellRenderConfig : {
		clazz : function(conf) {
			var operHandler = new OperHandler(conf);
			var delLink = tt_createGridDelBtn(conf.cell);

			talent.Util.addEventHandler(delLink, "click", operHandler.del);
		}
	}
};



var JsonUti = {
	// 定义换行符
	n : "\n",
	// 定义制表符
	t : "\t",
	// 转换String
	convertToString : function(obj) {
		return JsonUti.__writeObj(obj, 1);
	},
	// 写对象
	__writeObj : function(obj // 对象
	, level // 层次（基数为1）
	, isInArray) { // 此对象是否在一个集合内
		// 如果为空，直接输出null
		if (obj == null) {
			return "null";
		}
		// 为普通类型，直接输出值
		if (obj.constructor == Number || obj.constructor == Date || obj.constructor == String || obj.constructor == Boolean) {
			var v = obj.toString();
			var tab = isInArray ? JsonUti.__repeatStr(JsonUti.t, level - 1) : "";
			if (obj.constructor == String || obj.constructor == Date) {
				// 时间格式化只是单纯输出字符串，而不是Date对象
				return tab + ("\"" + v + "\"");
			} else if (obj.constructor == Boolean) {
				return tab + v.toLowerCase();
			} else {
				return tab + (v);
			}
		}
		// 写Json对象，缓存字符串
		var currentObjStrings = [];
		// 遍历属性
		for ( var name in obj) {
			var temp = [];
			// 格式化Tab
			var paddingTab = JsonUti.__repeatStr(JsonUti.t, level);
			temp.push(paddingTab);
			// 写出属性名
			temp.push("\"" + name + "\" : ");
			var val = obj[name];
			if (val == null) {
				temp.push("null");
			} else {
				var c = val.constructor;
				if (c == Array) { // 如果为集合，循环内部对象
					temp.push(JsonUti.n + paddingTab + "[" + JsonUti.n);
					var levelUp = level + 2; // 层级+2
					var tempArrValue = []; // 集合元素相关字符串缓存片段
					for (var i = 0; i < val.length; i++) {
						// 递归写对象
						tempArrValue.push(JsonUti.__writeObj(val[i], levelUp, true));
					}
					temp.push(tempArrValue.join("," + JsonUti.n));
					temp.push(JsonUti.n + paddingTab + "]");
				} else if (c == Function) {
					temp.push("[Function]");
				} else {
					// 递归写对象
					temp.push(JsonUti.__writeObj(val, level + 1));
				}
			}
			// 加入当前对象“属性”字符串
			currentObjStrings.push(temp.join(""));
		}
		return (level > 1 && !isInArray ? JsonUti.n : "") // 如果Json对象是内部，就要换行格式化
				+ JsonUti.__repeatStr(JsonUti.t, level - 1) + "{" + JsonUti.n // 加层次Tab格式化
				+ currentObjStrings.join("," + JsonUti.n) // 串联所有属性值
				+ JsonUti.n + JsonUti.__repeatStr(JsonUti.t, level - 1) + "}"; // 封闭对象
	},
	__isArray : function(obj) {
		if (obj) {
			return obj.constructor == Array;
		}
		return false;
	},
	__repeatStr : function(str, times) {
		var newStr = [];
		if (times > 0) {
			for (var i = 0; i < times; i++) {
				newStr.push(str);
			}
		}
		return newStr.join("");
	}
};

var setting = {
	view : {
		// addHoverDom : treeNodeAddHoverDom,
		// removeHoverDom : treeNodeRemoveHoverDom,
		selectedMulti : false,
		nameIsHTML : true,
		showLine : true,
		showTitle : true,
		showIcon : false
	},

	edit : {
	// enable : true
	},

	data : {
		simpleData : {
			enable : true,
			pIdKey : "pId"
		}
	},
	callback : {
		// onRightClick : myOnRightClick,
		onClick : treeNodeClicked
	}
};

/**
 * 
 * @param {}
 *            jsonData
 */
function fillWithJsonData(jsonData) {
	
	
	removeField('headerTable', 'headerTableBody', 'header', true);
	removeField('fieldTable', 'fieldTableBody', 'param', true);
	removeField('respremarkTable', 'respremarkTableBody', 'respremark', true);
	
	document.getElementById("headerTableHeader").style.display = "none";
	document.getElementById("fieldTableHeader").style.display = "none";
	document.getElementById("respremarkTableHeader").style.display = "none";
	
	
	document.getElementById("requestheaderTr").style.display = "none";
	document.getElementById("requestparamTr").style.display = "none";
	document.getElementById("requestbodyTr").style.display = jsonData.tt_requestbody ? "" : "none";
	document.getElementById("respremarkTr").style.display = "none";
	document.getElementById("remarkTr").style.display = jsonData.tt_remark ? "" : "none";
	
	document.getElementById("response_div").style.display = "none";
	
	document.getElementById("tt_requestbody").innerHTML = jsonData.tt_requestbody || '';
	document.getElementById("tt_remark").innerHTML = jsonData.tt_remark || '';
	document.getElementById("tt_method").innerHTML = jsonData.tt_method || '';
	document.getElementById("tt_request_url").innerHTML = jsonData.url || '';
	

	talent_c_setInputValueWithDataObj(jsonData, "", "", document.getElementById("urlForm"));
	
	
	
	// 格式化显示
	if (jsonData.resp_demo) {
		document.getElementById("response_div").style.display = "";
		var container = document.getElementById("html_container_json");
		container.innerHTML = "";
		document.getElementById("html_container").innerHTML = jsonData.resp_demo;
		try {
			var json = JSON.parse(jsonData.resp_demo);
			var jsonString = JsonUti.convertToString(json);
			showCode(jsonString, container);
		} catch (e) {
			console.log(e);
			container.innerHTML = jsonData.resp_demo;
		}
	}
	
	

	var requestHeaders = jsonData.requestHeaders;
	if (requestHeaders) {
		for ( var i in requestHeaders) {
			document.getElementById("requestheaderTr").style.display = "";
			document.getElementById("headerTableHeader").style.display = "";
			
			var h = requestHeaders[i];
			if (talent_isSpecifiedType(h, "String")){
				addField('headerTable', 'headerTableBody', 'header', i, h, null, null);
			} else {
				addField('headerTable', 'headerTableBody', 'header', i, h.value, h.remark, null);
			}
		}
	}

	var requestParams = jsonData.requestParams;
	if (requestParams) {
		for ( var i in requestParams) {
			document.getElementById("requestparamTr").style.display = "";
			document.getElementById("fieldTableHeader").style.display = "";
			var p = requestParams[i];
			var isArray = talent_isSpecifiedType(p, "Array");
			if (isArray) {
				for (var j = 0; j < p.length; j++) {
					 var pv = p[j];
					if (talent_isSpecifiedType(pv, "String")){
						addField('fieldTable', 'fieldTableBody', 'param', i, pv);
					} else {
						addField('fieldTable', 'fieldTableBody', 'param', i, pv.value, pv.remark);
					}
					
				}
			} else {
				if (talent_isSpecifiedType(p, "String")){
					addField('fieldTable', 'fieldTableBody', 'param', i, p);
				} else {
					addField('fieldTable', 'fieldTableBody', 'param', i, p.value, p.remark);
				}
				
			}
		}
	}
	
	
	var respremark = jsonData.respremark;
	if (respremark) {
		for ( var i in respremark) {
			document.getElementById("respremarkTableHeader").style.display = "";
			document.getElementById("respremarkTr").style.display = "";
			var p = respremark[i];
			var isArray = talent_isSpecifiedType(p, "Array");
			if (isArray) {
				for (var j = 0; j < p.length; j++) {
					 var pv = p[j];
					if (talent_isSpecifiedType(pv, "String")){
						addField('respremarkTable', 'respremarkTableBody', 'respremark', i, pv);
					} else {
						addField('respremarkTable', 'respremarkTableBody', 'respremark', i, pv.value, pv.remark);
					}
					
				}
			} else {
				if (talent_isSpecifiedType(p, "String")){
					addField('respremarkTable', 'respremarkTableBody', 'respremark', i, p);
				} else {
					addField('respremarkTable', 'respremarkTableBody', 'respremark', i, p.value, p.remark);
				}
				
			}
		}
	}

}

function loadTemplate(data) {
	document.getElementById("my_page_container").style.display = '';
	
	fillWithJsonData(data);
}

function treeNodeClicked(event, treeId, treeNode, clickFlag) {
	if (!treeNode.isdir) {
		
		openTab(treeNode.name, "./httpclient-lixian2.html?id=" + encodeURIComponent(treeNode.id), treeNode.id, null, true);
		
		
//		document.getElementById("templateName").innerHTML = treeNode.name;
//		loadTemplate(JSON.parse(treeNode.data));
	}
}
var zTreeObj;
function loadAllTemplate(callback) {
	zTreeObj = $.fn.zTree.init($("#menuTree"), setting, httpclient_data);
	zTreeObj.expandNode(getRoot(), true, false, true);
	if (selectedNodes && selectedNodes.length > 0) {
		for (var i = 0; i < selectedNodes.length; i++) {
			zTreeObj.selectNode(selectedNodes[i]);
			// document.getElementById("templateName").value = "";
			// treeNodeClicked(null, null, selectedNodes[i], null);
		}
	}

	if (callback) {
		callback.call(callback, zTreeObj);
	}
}

function getRoot() {
    var treeObj = $.fn.zTree.getZTreeObj("menuTree");
    //返回一个根节点
   return treeObj.getNodesByFilter(function (node) { return node.level == 0 }, true);
}

/**
 * 全部展开| 全部收起
 */
function expandNode(e) {
	var zTree = $.fn.zTree.getZTreeObj("menuTree");
	if (!zTree) {
		return;
	}
	var type = e.data.type;

	if (type == "expandAll") {
		zTree.expandAll(true);
	}
	if (type == "collapseAll") {
		zTree.expandAll(false);
	}
}

function init() {
	$("#expandAllBtn").bind("click", {
		type : "expandAll"
	}, expandNode);
	$("#collapseAllBtn").bind("click", {
		type : "collapseAll"
	}, expandNode);

	loadAllTemplate();

	

}
var selectedNodes;
function refreshAllTemplate() {
	var zTree = $.fn.zTree.getZTreeObj("menuTree");
	if (zTree) {
		selectedNodes = zTree.getSelectedNodes();
	}
	document.getElementById("menuTree").innerHTML = "";
	loadAllTemplate();

}




/* 打开一个标签 */
function openTab(title, _url, id, icon, _closable) {
	 if ($("#tabs").tabs('exists', title)) {
		 $("#tabs").tabs('select', title);
		 return;
	 }
	 
	var _content = "";
		/**
		 * 如果这个标题的标签存在，则选择该标签 否则添加一个标签到标签组
		 */
		var _c = _closable != false;

		var newtitle = title;
		$("#tabs").tabs('add', {
					title : newtitle,
					content : createTabContent(_url),
					closable : _c,
					id : id,
					icon : icon
				});
	
}

/* 生成标签内容 */
function createTabContent(url) {
	return '<iframe style="width:100%;height:100%;" scrolling="auto" frameborder="0" src="'
			+ url + '"></iframe>';
}




$(function() {
	init();

});
